/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

/**
 * <p>Project: javaseapp - Ex9
 * <p>Powered by webrx On 2021-08-26 08:43:22
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 16
 */
public class Ex9 {
    Object lock = new Object();

    public static void main(String[] args) {
        var ex = new Ex9();
        new Thread(ex::work, "T1").start();
        new Thread(ex::work, "T2").start();
        new Thread(ex::work, "T3").start();
        new Thread(ex::work, "T4").start();
        new Thread(ex::work, "ok").start();
    }

    void work() {
        synchronized (lock) {
            String tn = Thread.currentThread().getName();
            if ("ok".equals(tn)) {
                //lock.notifyAll(); 唤醒所有wait后线程
                lock.notify();//唤醒一个就绪线程
            } else {
                for (int i = 0; i < 3; i++) {
                    System.out.printf("%s = %d%n", tn, i);
                    try {
                        lock.wait(); //没有唤醒   notify()
                        //TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
